package com.lhh.springcommon.utils;

import com.lhh.springcommon.config.JwtConfigurationProperties;
import com.lhh.springcommon.exception.CustomException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 * @author 李厚航
 */
@Component
public class JwtUtil {

    private final JwtConfigurationProperties jwtConfigurationProperties;

    @Autowired
    public JwtUtil(JwtConfigurationProperties jwtConfigurationProperties) {
        this.jwtConfigurationProperties = jwtConfigurationProperties;
    }

    /**
     * jwt 加解密类型
     */
    private final SecureDigestAlgorithm<SecretKey,SecretKey> ALGORITHM = Jwts.SIG.HS256;

    /**
     * 生成token
     * @param map
     * @return
     */
    public String createToken(Map<String,Object> map){
        return Jwts.builder()
                .signWith(generalKey(),ALGORITHM)
                .issuer(jwtConfigurationProperties.getUtils().getIssue())
                .expiration(new Date(System.currentTimeMillis()+jwtConfigurationProperties.getUtils().getTimeout()*1000L))
                .claims(map)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Jws<Claims> getClaimsBody(String token){
        try{
            return Jwts.parser()
                    .verifyWith(generalKey())
                    .build()
                    .parseSignedClaims(token);
        }catch (Exception e){
            throw new CustomException(CodeEnum.TOKEN_VERIFICATION_FAILED);
        }

    }

    /**
     * 生成加密密钥
     * @return 加密后的密钥
     */
    public SecretKey generalKey(){
        byte[] encode = jwtConfigurationProperties.getUtils().getSecret().getBytes();
        return Keys.hmacShaKeyFor(encode);
    }

}
